package com.wn.service.impl;

import com.wn.bean.DataRoleBean;
import com.wn.bean.R;
import com.wn.bean.Role;
import com.wn.bean.RolePermission;
import com.wn.mapper.RoleMapper;
import com.wn.service.IRolePermissionService;
import com.wn.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yellow Docter
 * @since 2022-05-16
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private IRolePermissionService permissionService;

    /**
     *  添加业务逻辑
     *  01 添加role
     *
     *  02 添加role对应的权限表
     *
     * @param dataRoleBean
     * @return
     */
    @Override
    @Transactional
    public R addRole(DataRoleBean dataRoleBean) {

        // 01 添加role
        Role role = dataRoleBean.getRole();
        boolean save = save(role);
        if (!save){
            throw new RuntimeException();
        }

        //02 添加 rolePermisson
        List<Integer> pids = dataRoleBean.getPids();

        //创建 role_permission 对象
        Integer rid = role.getRid();
        List<RolePermission> rolePermissions =new ArrayList<>();

        for (Integer pid : pids) {
            rolePermissions.add(new RolePermission(rid,pid));
        }

        boolean b = permissionService.saveBatch(rolePermissions);
        if (!b){
            throw new RuntimeException();
        }
        return R.OK("添加角色成功");

    }
}
